<?php

namespace app\api\controller;

use app\api\model\User as UserModel;

/**
 * 用户管理
 * Class User
 * @package app\api
 */
class User extends Controller
{
//    /**
//     * 用户自动登录
//     * @return array
//     * @throws \app\common\exception\BaseException
//     * @throws \think\Exception
//     * @throws \think\exception\DbException
//     */
//    public function login()
//    {
//        $model = new UserModel;
//        return $this->renderSuccess([
//            'user_id' => $model->login($this->request->post()),
//            'token' => $model->getToken()
//        ]);
//    }

    /**
     * 当前用户详情
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        return $this->renderSuccess(compact('userInfo'));
    }

    protected $appid = 'wxb86be572e371fc38';
    protected $appSecert = '77310c7f8d034ba314ac6b25853ab875';

    /**
     * 用户详细授权，access_token
     */
    public function wxtoken()
    {
        //GET（请使用https协议） https://api.weixin.qq.com/cgi-bin/token?appid=APPID&secret=SECRET&grant_type=authorization_code
        $grant_type = 'client_credential';
        $httpUrl = 'https://api.weixin.qq.com/cgi-bin/token';
        $httpUrl .= '?appid=' . $this->appid;
        $httpUrl .= '&secret=' . $this->appSecert;
        $httpUrl .= '&grant_type=' . $grant_type;
        $resCurl = $this->wxCurl($httpUrl);
        if ($resCurl['code'] < 0) {
            $this->error('wx error', '', $resCurl);
        }
        $access_token = $resCurl['data']['access_token'];
        //获取openid
        //GET https://api.weixin.qq.com/sns/jscode2session?appid=&secret=&js_code=&grant_type=authorization_code
        $code = $this->request->param('code');
        if (!$code) {
            $this->throwError('没有code', -2);
        }
        $httpUrl = 'https://api.weixin.qq.com/sns/jscode2session';
        $httpUrl .= '?appid=' . $this->appid;
        $httpUrl .= '&secret=' . $this->appSecert;
        $httpUrl .= '&js_code=' . $code;
        $httpUrl .= '&grant_type=authorization_code';
        $resCurl = $this->wxCurl($httpUrl);
        if ($resCurl['code'] < 0) {
            $this->error('wx error', '', $resCurl);
        }
        $resData = [
            'access_token' => $access_token,
            'openid' => $resCurl['data']['openid'],
        ];
        $this->success('', '', $resData);
    }

    /**
     * 获取手机号
     */
    public function wxphone()
    {
        $access_token = $this->request->param('access_token');
        $code = $this->request->param('code');
        if (!$access_token) {
            $this->throwError('没有access_token', -2);
            return false;
        }
        if (!$code) {
            $this->throwError('没有code', -2);
            return false;
        }
        //获取手机号
        //POST https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
        $httpUrl = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber';
        $httpUrl .= '?access_token=' . $access_token;
        $postData = json_encode([
            'code' => $code,
        ], JSON_UNESCAPED_UNICODE);
        $resPhone = $this->wxCurl($httpUrl, 1, $postData);
        if ($resPhone['code'] < 0) {
            $this->error('wx error', '', $resPhone);
        }
        if ($resPhone['data']['errcode'] != 0) {
            $this->error('wx error', '', $resPhone);
        }
        $resData = [
            'phone' => $resPhone['data']['phone_info']['phoneNumber'],
        ];
        $this->success('', '', $resData);
    }

    /**
     * 保存微信信息
     */
    public function wxsave()
    {
        $nick = $this->request->param('nick');
        $phone = $this->request->param('phone');
        $openid = $this->request->param('openid');
        if (!$phone) {
            $this->error('手机号必须的');
        }
        if (!$nick) {
            $nick = '微信昵称' . date('YmdHis', time()) . rand(100, 999);
        }
        $model = new UserModel;
        $res = $model->wxSave($nick, $phone, $openid);
        if ($res['code'] < 0) {
            $this->error($res['msg']);
        }
        $this->success('success', '', $res['data']);
    }

    /**
     * 获取微信信息
     */
    public function uinfo()
    {
        $user_id = $this->request->param('user_id');
        if (!$user_id) {
            $this->error('用户ID必须的');
        }
        $model = new UserModel;
        $res = $model->wxOne($user_id);
        if ($res['code'] < 0) {
            $this->error($res['msg']);
        }
        $this->success('success', '', $res['data']);
    }

    /**
     * 构建CURL请求，单线程
     * @param $url 请求地址
     * @param $method 请求方式：0get，1post
     * @param $sring 请求数据
     * @return $json
     */
    public function wxCurl($url, $method = 0, $string = '')
    {
        $curl = curl_init(); //初始化
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        if ($method) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $string);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        if (!$output) {
            return array('code'=> -1, 'msg'=>'请求失败');
        }
        $items = json_decode($output,true);
        return array('code' => 0, 'msg' => 'success', 'data' => $items);
    }
}